package bairui.international.weixin.portal.miniapp.config;

import java.lang.reflect.InvocationTargetException;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.metamodel.EmbeddableType;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import com.lianjing.sh.model.common.stardard.CompositePrimaryKey;

@Configuration
public class Config_WebMvcConfiguration extends WebMvcConfigurationSupport {

	@PersistenceContext private EntityManager entityManager;
	
	@Override 
	public void addFormatters(FormatterRegistry registry) {
		/**
		 * 处理复合主键数据绑定转换
		 */
		for(EmbeddableType<?> item : entityManager.getMetamodel().getEmbeddables()){
			Class<?> javaType = item.getJavaType();
			if(CompositePrimaryKey.class.isAssignableFrom(javaType)){
				// 添加转换器
				try {
					registry.addConverter((Converter<?,?>)javaType.getMethod("convert").invoke(null));
				} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
					throw new RuntimeException(e);
				}
			}
		}
    }
	
}
